import React from 'react';
import { Table } from 'antd';
import type { TableProps, ColumnsType } from 'antd/es/table';
import { useScrollHeight } from '@/hooks';

export interface DataTableProps<T = any> extends Omit<TableProps<T>, 'columns' | 'dataSource'> {
  columns: ColumnsType<T>;
  dataSource: T[];
  loading?: boolean;
  pagination?: {
    current: number;
    pageSize: number;
    total: number;
    showSizeChanger?: boolean;
    showQuickJumper?: boolean;
  };
  onPageChange?: (page: number, pageSize: number) => void;
  rowKey?: string | ((record: T) => string);
  autoHeight?: boolean; // 是否自动计算高度
  heightOffset?: number; // 高度偏移量，默认 320
}

function DataTable<T extends Record<string, any>>({
  columns,
  dataSource,
  loading,
  pagination,
  onPageChange,
  rowKey = 'id',
  autoHeight = true,
  heightOffset = 520,//480
  scroll,
  ...restProps
}: DataTableProps<T>) {
  const scrollY = useScrollHeight(heightOffset);

  const handleTableChange = (page: number, pageSize: number) => {
    if (onPageChange) {
      onPageChange(page, pageSize);
    }
  };

  // 确保分页参数有效
  const validPagination = pagination
    ? {
        current: Math.max(1, pagination.current || 1),
        pageSize: Math.max(1, pagination.pageSize || 20),
        total: Math.max(0, pagination.total || 0),
        showSizeChanger: pagination.showSizeChanger !== false,
        showQuickJumper: pagination.showQuickJumper !== false,
        pageSizeOptions: ['10', '20', '50', '100'],
        showTotal: (total: number) => `共 ${total} 条`,
        onChange: handleTableChange,
        onShowSizeChange: handleTableChange,
      }
    : false;

  // 合并 scroll 配置，自动添加 y 轴滚动
  const finalScroll = autoHeight
    ? { ...scroll, y: scroll?.y || scrollY }
    : scroll;

  return (
    <Table
      columns={columns}
      dataSource={dataSource}
      rowKey={rowKey}
      loading={loading}
      pagination={validPagination}
      scroll={finalScroll}
      {...restProps}
    />
  );
}

export default DataTable;

